<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-form :inline="true" :model="searchForm" ref="searchForm" class="demo-form-inline" size="small">
        <el-form-item label="">
          <el-select v-model="searchForm.plat_id" clearable placeholder="选择平台方" @change="((val)=>{platChange(val,'searchOperateList')})">
            <el-option v-for="(item) in platList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="operate_id" ref="searchOperateList">
          <el-select v-model="searchForm.operate_id" clearable placeholder="选择运营方">
            <el-option v-for="(item) in searchOperateList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.stop="search">搜索</el-button>
          <el-button type="primary" @click.stop="reload">刷新</el-button>
          <el-button type="primary" @click.stop="add">添加</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="table" border size="small">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="学校名称"></el-table-column>
        <el-table-column label="logo" width="125">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.logo" fit="fill" :preview-src-list="[scope.row.logo]"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="delivery" label="固定配送费">
          <template slot-scope="scope">{{scope.row.delivery}}元</template>
        </el-table-column>
        <el-table-column prop="percentage" label="百分比配送费">
          <template slot-scope="scope">{{scope.row.percentage}}%</template>
        </el-table-column>
        <el-table-column prop="limit" label="配送费加成限额">
          <template slot-scope="scope">{{scope.row.limit}}元</template>
        </el-table-column>
        <el-table-column prop="company" label="公司百分比">
          <template slot-scope="scope">{{scope.row.company}}%</template>
        </el-table-column>
        <el-table-column prop="plat" label="平台方百分比">
          <template slot-scope="scope">{{scope.row.plat}}%</template>
        </el-table-column>
        <el-table-column prop="operate" label="运营方百分比">
          <template slot-scope="scope">{{scope.row.operate}}%</template>
        </el-table-column>
        <el-table-column prop="extension" label="推广反比">
          <template slot-scope="scope">{{scope.row.extension}}%</template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page" :page-sizes="[10,20,30,40]" :page-size="searchForm.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="count">
        </el-pagination>
      </div>
      <el-dialog title="添加学校" :visible.sync="addVisible" width="500px" :before-close="handleClose('addForm')">
        <el-form ref="addForm" :model="addForm" label-width="140px" size="small" :rules="rules">
          <el-form-item label="学校名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="学校logo">
            <el-upload ref="addLogo" name="image" :action="action" :before-upload="beforeUpload" :on-success="((response, file, fileList)=>{handleSuccess(response, file, fileList,'addLogo')})" :on-error="handleError"
              :before-remove="beforeRemove" :file-list="fileList" list-type="picture" :data="imgData" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="平台方" prop="plat_id" ref="add_plat">
            <el-select v-model="addForm.plat_id" clearable placeholder="选择平台方" @change="((val)=>{platChange(val,'addOperateList')})">
              <el-option v-for="(item) in platList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运营方" prop="operate_id" ref="addOperateList">
            <el-select v-model="addForm.operate_id" clearable placeholder="选择运营方">
              <el-option v-for="(item) in addOperateList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送费加成限额" prop="limit">
            <el-input v-model="addForm.limit"></el-input>
          </el-form-item>
          <el-form-item label="固定配送费" prop="delivery">
            <el-input v-model="addForm.delivery"></el-input>
          </el-form-item>
          <el-form-item label="百分比配送费" prop="percentage">
            <el-input v-model="addForm.percentage"></el-input>
          </el-form-item>
          <el-form-item label="公司百分比" prop="company">
            <el-input v-model="addForm.company"></el-input>
          </el-form-item>
          <el-form-item label="平台方百分比" prop="plat">
            <el-input v-model="addForm.plat"></el-input>
          </el-form-item>
          <el-form-item label="运营方百分比" prop="operate">
            <el-input v-model="addForm.operate"></el-input>
          </el-form-item>
          <el-form-item label="推广反比" prop="extension">
            <el-input v-model="addForm.extension"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑学校" :visible.sync="editVisible" width="500px" :before-close="handleClose('editForm')">
        <el-form ref="editForm" :model="editForm" label-width="140px" size="small" :rules="rules">
          <el-form-item label="学校名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="学校logo">
            <el-upload ref="editLogo" name="image" :action="action" :before-upload="beforeUpload" :on-success="((response, file, fileList)=>{handleSuccess(response, file, fileList,'editLogo')})" :on-error="handleError"
              :before-remove="beforeRemove" :file-list="fileList" list-type="picture" :data="imgData" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="平台方" prop="plat_id" ref="edit_plat">
            <el-select v-model="editForm.plat_id" clearable placeholder="选择平台方" @change="((val)=>{platChange(val,'editOperateList')})">
              <el-option v-for="(item) in platList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运营方" prop="operate_id" ref="editOperateList">
            <el-select v-model="editForm.operate_id" clearable placeholder="选择运营方">
              <el-option v-for="(item) in editOperateList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送费加成限额" prop="limit">
            <el-input v-model="editForm.limit"></el-input>
          </el-form-item>
          <el-form-item label="固定配送费" prop="delivery">
            <el-input v-model="editForm.delivery"></el-input>
          </el-form-item>
          <el-form-item label="百分比配送费" prop="percentage">
            <el-input v-model="editForm.percentage"></el-input>
          </el-form-item>
          <el-form-item label="公司百分比" prop="company">
            <el-input v-model="editForm.company"></el-input>
          </el-form-item>
          <el-form-item label="平台方百分比" prop="plat">
            <el-input v-model="editForm.plat"></el-input>
          </el-form-item>
          <el-form-item label="运营方百分比" prop="operate">
            <el-input v-model="editForm.operate"></el-input>
          </el-form-item>
          <el-form-item label="推广反比" prop="extension">
            <el-input v-model="editForm.extension"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { formatDate } from '@/untils/common.js'
import { platSimpleList, operateSimpleList, delImg, schoolList, schoolFind, deleteSchool, schoolIncrease, schoolEdit } from '@/network/api.js'

export default {
  name: 'school',
  data () {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        plat_id: '',
        operate_id: ''
      },
      action: process.env.NODE_ENV === 'development' ? 'http://dxsd.test.com/school/upload_img' : '/school/upload_img',
      count: 0, // 总记录数
      table: [],
      platList: [],
      searchOperateList: [],
      addOperateList: [],
      editOperateList: [],
      operateListAll: [],
      imgData: {}, // 上传图片格外信息
      imgurl: '', // 上传以后图片路径
      fileList: [], // 上传列表
      type: '', // 操作类型 add edit
      addForm: {
        name: '', // 学校名称
        logo: '', // 学校logo
        plat_id: '',
        operate_id: '',
        limit: 20, // 配送费加成限额
        delivery: 0.01, // 固定配送费
        percentage: 0.1, // 百分比配送费
        company: 1.2, // 公司百分比
        plat: 3.8, // 平台方百分比
        operate: 5, // 运营方百分比
        extension: 0.1 // 推广反比
      }, // 添加的表单
      editForm: {
        id: 0,
        name: '', // 学校名称
        logo: '', // 学校logo
        plat_id: '',
        operate_id: '',
        limit: '', // 配送费加成限额
        delivery: '', // 固定配送费
        percentage: '', // 百分比配送费
        company: '', // 公司百分比
        plat: '', // 平台方百分比
        operate: '', // 运营方百分比
        extension: '' // 推广反比
      }, // 编辑的表单
      addVisible: false, // 添加表单
      editVisible: false, // 编辑表单
      rules: {
        name: [
          { required: true, message: '请输入学校名称', trigger: 'blur' }
        ],
        plat_id: [
          { required: true, message: '请选择平台方', trigger: 'blur' }
        ],
        operate_id: [
          { required: true, message: '请选择运营方', trigger: 'blur' }
        ],
        limit: [
          { required: true, message: '请输入配送费加成限额', trigger: 'blur' }
        ],
        delivery: [
          { required: true, message: '请输入固定配送费', trigger: 'blur' }
        ],
        percentage: [
          { required: true, message: '请输入百分比配送费', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '请输入公司百分比', trigger: 'blur' }
        ],
        plat: [
          { required: true, message: '请输入平台方百分比', trigger: 'blur' }
        ],
        operate: [
          { required: true, message: '请输入运营方百分比', trigger: 'blur' }
        ],
        extension: [
          { required: true, message: '请输入推广反比', trigger: 'blur' }
        ]
      }
    }
  },
  async created () {
    try {
      const platRtn = await platSimpleList({})
      this.platList = platRtn.data
      const operateRtn = await operateSimpleList({})
      this.searchOperateList = operateRtn.data
      this.operateListAll = operateRtn.data
    } catch (e) {
      this.$message.error(e.message)
    }
    this.search()
  },
  computed: {
    statusName () {
      return (status) => {
        switch (status) {
          case 0: return '禁用'
          case 1: return '启用'
        }
      }
    },
    timeFormat () {
      return (time) => {
        return formatDate(time)
      }
    },
    // 返现值
    cashValue () {
      return (type, value) => {
        switch (type) {
          case 1: return value + ' 元'
          case 2: return value + ' %'
        }
      }
    }
  },
  methods: {
    reload () {
      location.reload()
    },
    async search () {
      try {
        const rtn = await schoolList(this.searchForm)
        this.table = rtn.data.list
        this.count = rtn.data.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    platChange (val, type) {
      this.$refs[type].resetField()
      if (val === '') {
        this[type] = this.operateListAll
      } else {
        this[type] = []
        for (const key in this.operateListAll) {
          if (this.operateListAll[key].pid === val) {
            this[type].push(this.operateListAll[key])
          }
        }
      }
    },
    // 每页条数变化
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.search()
    },
    // 上传成功
    handleSuccess (response, file, fileList, type) {
      if (response.code !== 200) {
        this.$message.error(response.msg)
        this.$refs[type].clearFiles() // 删除预览
      } else {
        this.imgurl = response.data
      }
    },
    // 上传失败
    handleError () {
      this.$message.error('上传失败')
    },
    // 上传前
    beforeUpload (file) {
      // 判断文件类型
      const imageType = ['image/png', 'image/jpeg', 'image/jpeg']
      if (imageType.indexOf(file.type) === -1) {
        this.$message.error('请上传png|jpg|jpeg图片')
        return false
      }
      this.imgData.token = this.$storage.get('token')
    },
    // 删除前
    async beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        // 移除方法
        try {
          const formdata = {
            imgurl: this.imgurl,
            type: 1,
            token: this.$storage.get('token')
          }
          if (this.type === 'edit') {
            formdata.id = this.editForm.id
          }
          await delImg(formdata)
          if (this.type === 'edit') {
            this.editForm.logo = ''
          } else {
            this.addForm.logo = ''
          }
          this.imgurl = ''
        } catch (e) {
          this.$message.error(e.message)
          return Promise.reject(new Error(e.message))
        }
      }
    },
    // 超出上传个数
    handleExceed (files, fileList) {
      this.$message.error('已有logo图片请先删除')
    },
    // 添加学校
    add () {
      this.type = 'add'
      this.addVisible = true
      this.$nextTick(() => {
        this.addOperateList = this.operateListAll
      })
    },
    // 编辑学校
    async edit (id) {
      try {
        const rtn = await schoolFind({ id })
        this.type = 'edit'
        this.editVisible = true
        this.fileList = []
        this.$nextTick(() => {
          this.editForm = rtn.data
          this.platChange(rtn.data.plat_id, 'editOperateList')
          if (rtn.data.logo !== '') {
            this.fileList.push({ url: rtn.data.logo })
            this.imgurl = rtn.data.logo
          }
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 删除
    async del (id) {
      try {
        await deleteSchool({ id })
        this.search()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose (formName) {
      return (done) => {
        this.$refs[formName].resetFields()
        this.fileList = []
        this[formName].logo = ''
        this.imgurl = ''
        done()
      }
    },
    // 取消按钮
    close (visibleName, formName) {
      this.$refs[formName].resetFields()
      this[visibleName] = false
      this[formName].logo = ''
      this.imgurl = ''
      this.fileList = []
    },
    send (visibleName, formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          switch (formName) {
            case 'addForm': // 添加表单
              try {
                this.addForm.logo = this.imgurl
                if (this.addForm.logo === '') {
                  return this.$message.error('请上传学校logo')
                }
                await schoolIncrease(this.addForm)
                this.close('addVisible', 'addForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'editForm': // 编辑表单
              try {
                this.editForm.logo = this.imgurl
                if (this.editForm.logo === '') {
                  return this.$message.error('请上传学校logo')
                }
                await schoolEdit(this.editForm)
                this.close('editVisible', 'editForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
</style>
